package com.littcore.saap.core.module.message.meta;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.littcore.common.CoreConstants;
import com.littcore.saap.core.common.SaapConstants;
import com.littcore.saap.core.module.portal.PortletMetaParam;
import com.littcore.util.ResourceUtils;
import com.littcore.util.StringUtils;
import com.thoughtworks.xstream.XStream;


/**
 * .
 * 
 * <pre><b>描述：</b>
 *    
 * </pre>
 * 
 * <pre><b>修改记录：</b>
 *    
 * </pre>
 * 
 * @author <a href="mailto:littcai@hotmail.com">蔡源</a>
 * @since 2015年10月28日
 * @version 1.0
 */
public class MessageMetaManager {

public static final Logger logger = LoggerFactory.getLogger(MessageMetaManager.class);
  
  public static String BASE_PATH = "message"; 
  
  private LinkedHashMap<String, MessageModule> messageModuleMap = new LinkedHashMap<String, MessageModule>();
    
  public MessageMetaManager()
  {
    init();
  }
  
  public void init()
  {
    logger.info("Init Message module...");
    //读取系统内置的
    {
      try {
        File dir = ResourceUtils.getFile("classpath:module/message");
        loadConfig(dir);
      } catch (FileNotFoundException e) {
        logger.error("Load portal config files from classpath failed.", e);
      }
    }
    
    //读取生产环境中保存的，相同的将覆盖系统内置的
    {
      File dir = new File(SaapConstants.HOME_PATH, BASE_PATH);
      loadConfig(dir);
    }     
  }

  private void loadConfig(File dir) 
  {
    if(dir.exists() && dir.isDirectory())
    {
      File[] files = dir.listFiles();
      for (File file : files) {       
        if(!StringUtils.endsWithIgnoreCase(file.getName(), ".xml"))
          continue;
        logger.debug("load message config file:{}", new Object[]{file.getName()});
        String name = StringUtils.substringBefore(file.getName(), "-message");
        
        XStream xstream = new XStream();
        xstream.alias("domain", MessageDomain.class);
        xstream.alias("module", MessageModule.class);
        xstream.alias("message", MessageMeta.class);
        xstream.alias("checkedChannels", String[].class);
        //xstream.alias("channel", String.class);
        xstream.addImplicitCollection(MessageDomain.class, "modules");
        xstream.addImplicitCollection(MessageModule.class, "metas");        
        xstream.aliasAttribute(MessageModule.class, "code", "code");
        xstream.aliasAttribute(MessageMeta.class, "code", "code");
        xstream.aliasAttribute(MessageMeta.class, "editable", "editable");        
        //xstream.addImplicitArray(MessageMeta.class, "channels");
        MessageDomain messageDomain = (MessageDomain)xstream.fromXML(file);
        List<MessageModule> modules = messageDomain.getModules();
        for (MessageModule messageModule : modules)
        {
          logger.debug("find module:{}", new Object[]{messageModule.getCode()});
          this.messageModuleMap.put(messageModule.getCode(), messageModule);
        }
        
      }
    }
  } 
  
  public void reload() {
    this.init();
  } 
  
  public MessageModule getMessageModule(String moduleCode)
  {
    if(CoreConstants.IS_DEBUG)
      this.init();
    return messageModuleMap.get(moduleCode);
  }
  
  public MessageMeta getMessageMeta(String moduleCode, String messageCode)
  {
    if(CoreConstants.IS_DEBUG)
      this.init();
    return messageModuleMap.get(moduleCode).getMessageMeta(messageCode);
  }
  
  public List<MessageModule> getAllMessageModules()
  {   
    if(CoreConstants.IS_DEBUG)
      this.init();
    return new LinkedList<MessageModule>(this.messageModuleMap.values());
  }
  
  
  public static void main(String[] args) throws Exception {
    MessageModule module = MessageMetaManager.getInstance().getMessageModule("tenantMember");
    System.out.println(module.getCode());
    System.out.println(module.getMessageMeta("delete").toString());
   
  }
  
  private static class SingletonClassInstance { 
      private static final MessageMetaManager instance = new MessageMetaManager(); 
  } 

  /**
   * Gets the single instance of QuickViewManager.
   *
   * @return single instance of QuickViewManager
   */
  public static MessageMetaManager getInstance() { 
      return SingletonClassInstance.instance; 
  }

}
